import { ref } from 'vue'
import { getinventoryquery_api } from '@/axios/api/slot_management/inventoryQuery'
import { ElNotification } from 'element-plus';
import { useSlotManagementStore } from '@/store/slot_mangement';
const SlotManagementStore = useSlotManagementStore();
import * as XLSX from 'xlsx';

export default function () {

    let loction = ref('')


    async function getquery() {
        SlotManagementStore.inventoryQuery_pinia = []
        try {
            let loction_query = loction.value.trim();
            let flag = 0;
            if (loction_query.valueOf() !== '') {
                flag = 1;
            }
            let res: any = await getinventoryquery_api({ loction: loction_query, flag: flag })
            if (res.code === 200) {
                SlotManagementStore.inventoryQuery_pinia = JSON.parse(res.data);
                return 'ok';
            } else {
                ElNotification({
                    title: 'Error',
                    message: res.message,
                    type: 'error',
                })
                return Promise.reject(new Error(res.msg))
            }
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
            return Promise.reject(new Error(error))
        }
    }

    // 导出excel
    const exportExcel = async () => {
        if (SlotManagementStore.inventoryQuery_pinia.length == 0) {
            ElNotification({
                title: 'Error',
                message: '没有数据',
                type: 'error',
            })
            return;
        }

        const ws = XLSX.utils.json_to_sheet(SlotManagementStore.inventoryQuery_pinia); // 将数据转换为工作表
        const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

        // 创建Blob对象并使用URL.createObjectURL方法生成URL
        const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const url = URL.createObjectURL(data);

        // 创建隐藏的可下载链接
        const link = document.createElement('a');
        link.href = url;
        link.style.display = 'none';
        link.download = 'data.xlsx'; // 设置下载文件名
        document.body.appendChild(link);

        // 触发点击下载
        link.click();
        // 清理
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        }, 100);
    }

    return {
        loction,
        getquery,
        exportExcel
    }
}